<?php

use think\Db;

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}
/*
 * 积分变动
 */
function change_user_score_log($user_id, $score, $memo, $order_sn = '', $order_id = 0)
{
    $before = Db::name('user')->where(['id' => $user_id])->value('score');
    $after = intval($before) + intval($score);
    $data = [
        'user_id' => $user_id,
        'score' => $score,
        'before' => $before,
        'after' => $after,
        'memo' => $memo,
        'createtime' => time(),
        'order_sn' => $order_sn,
        'order_id' => $order_id

    ];
    $res = Db::name('user_score_log')->insert($data);


    $signScore = Db::name('config')->where(['name' => 'sign_score'])->value('value');

    $score = intval($score);
    $update_data = [
        "score" => Db::raw("score+$score")
    ];
    Db::name('user')->where('id', $user_id)->update($update_data);


}

/*
 * 余额变动
 */
function change_user_account_log($user_id, $account, $memo, $order_sn = '', $order_id = 0)
{
    $before = Db::name('user')->where(['id' => $user_id])->value('account');
    $after = ($before*100 + $account*100)/100;
    $data = [
        'user_id' => $user_id,
        'account' => $account,
        'before' => $before,
        'after' => $after,
        'memo' => $memo,
        'createtime' => time(),
        'order_sn' => $order_sn,
        'order_id' => $order_id

    ];

    Db::name('user_account_log')->insert($data);
    Db::name('user')->where('id', $user_id)->update(["account" => $after]);
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }

}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
            if (is_bool($domain)) {
                $public = \think\Config::get('view_replace_str.__PUBLIC__');
                $url = rtrim($public, '/') . $url;
                if (!preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
                    $url = request()->domain() . $url;
                }
            } else {
                $url = $domain . $url;
            }
        }
        return $url;
    }

}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === FALSE) {
                return FALSE;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return TRUE;
        } elseif (!is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) {
            return FALSE;
        }
        fclose($fp);
        return TRUE;
    }

}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname))
            return false;
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }

}

if (!function_exists('mb_ucfirst')) {

    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }

}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields)
            return $items;
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }

}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }

}

//写入礼物表
function add_gift($order){
    $order['master_order_sn'] ? $order_sn = $order['master_order_sn'] : $order_sn=$order['order_sn'];
    empty($order['type']) ? $status = '1': $status = '0' ;
    $data = [
        'order_id' => $order['id'],
        'goods_id' => $order['goods_id'],
        'user_id' => $order['user_id'],
        'type' => $order['type'],
        'price' => $order['goods_price'],
        'createtime' => time(),
        'order_sn' => $order_sn,
        'status' => $status
    ];

    Db::name('gift')->insert($data);

}

//下单送积分
function give_integral($order){
    $goods = Db::name('goods')->where('id',$order['goods_id'])->find();
    //订单未使用积分情况送积分
    if(!$order['integral']){
        $memo = "下单赠送积分";

        if($goods['give_integral'] > 0){
            change_user_score_log($order['user_id'], $goods['give_integral'], $memo, $order['order_sn'], $order['id']); //积分记录表
        }

    }

}

//平台资金记录表
function change_expense($account,$user_id){
    Db::name('expense')->insert([
        'admin_id' => 0,
        'account' => $account,
        'user_id' => $user_id,
        'createtime' => time(),
        'type' => '0',
        'note' => '订单支付' . $account. '元'
    ]);
}


function update_pay_status($order_sn, $transaction_id = '')
{
    //    先查看一下 是不是 合并支付的主订单号
    $order_list = Db::name('order')->where("master_order_sn", $order_sn)->select();
    if ($order_list) {
        foreach ($order_list as $key => $val)
            update_pay_status($val['order_sn'], $transaction_id);
        return;
    }
    // 找出对应的订单
    $order = Db::name('order')->where(['order_sn' => $order_sn, 'pay_status' => 0])->find();   // 看看有没已经处理过这笔订单  微信返回不重复处理操作
    if (empty($order)) return false; //如果这笔订单已经处理过了
    // 修改支付状态  已支付
    Db::name('order')->where("order_sn", $order_sn)->update(['pay_status' => 1, 'order_status' => 1,'pay_time' => time(), 'transaction_id' => $transaction_id]);

//    if($order['type'] == 1 || $order['type'] == 2){
//        add_gift($order);
//
//    }
    add_gift($order);

    if (intval($order['integral']) > 0) {
        //订单使用积分

        //积分记录
        $memo = '订单使用积分';
        change_user_score_log($order['user_id'], '-' . $order['integral'], $memo, $order['order_sn'], $order['id']); //积分记录表
    }

    //减少对应商品的库存
    minus_stock($order);

    // 赠送积分
    give_integral($order);

    //写入资金记录表
    change_expense($order['total_amount'],$order['user_id']);

}

/**
 * 扣除商品库存，更新活动商品
 * @param type $order_id 订单id
 */
function minus_stock($order)
{

    Db::name('goods')->where('id', $order['goods_id'])->setDec('store_count', $order['goods_num']);
    Db::name('goods')->where('id', $order['goods_id'])->setInc('sales_sum', $order['goods_num']);

    $goodsM = new \app\common\model\Goods();
    $goods = $goodsM->get($order['goods_id']);

    //更新活动商品购买量
    if ($order['order_prom_type'] == 1 || $order['order_prom_type'] == 3) {
        $GoodsPromFactory = new \app\common\logic\GoodsPromFactory();
        $goodsPromLogic = $GoodsPromFactory->makeModule($goods);
        $prom = $goodsPromLogic->getPromModel();
        if ($prom['status'] == 1 && $prom['is_end'] == 0) {
            $tb = $order['order_prom_type'] == 1 ? 'cutdown' : 'flash_sale';
            Db::name($tb)->where("id", $order['prom_id'])->setInc('sales_sum', $order['goods_num']);
            Db::name($tb)->where("id", $order['prom_id'])->setInc('buy_num');

        }
    }

    if ($order['order_prom_type'] == 2) {
        Db::name('team_activity')->where('id', $order['order_prom_id'])->setInc('sales_sum', $order['goods_num']);

        //拼团支付后操作,修改开团或参团表状态
        $order = \app\common\model\Order::get($order['id']);
        $TeamOrderLogic = new \app\common\logic\TeamOrderLogic();
        $TeamOrderLogic->doOrderPayAfter($order);

    }


}


/**
 *      把秒数转换为时分秒的格式
 *      @param Int $times 时间，单位 秒
 *      @return String
 */
function secToTime($times){
    $result = '00:00:00';
    if ($times>0) {
        $hour = floor($times/3600);
        $minute = floor(($times-3600 * $hour)/60);
        $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
        $result = $hour.':'.$minute.':'.$second;
    }
    return $result;
}



if (!function_exists('send_sms')) {
    /**
     * 发送短信
     * @param $mobile
     * @param $code
     * @param $type 1 验证码 2 通知
     */
    function send_sms($mobile, $event = 'register', $code = '', $type = 1, $content = '')
    {

        if (!check_mobile($mobile)) {
            return $res = [
                'code' => '-1',
                'msg' => '手机号码格式不正确',
                'data' => '',
            ];
        }
        $event = empty($event) ? 'register' : $event;
        $code = empty($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $smsModel = new \app\common\model\Sms();
        $sms = $smsModel->save(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'createtime' => $time]);

        $a = new \app\common\model\SmsLogic();

        if ($type == 1) {
            $content = "尊敬的用户, 您的验证码： " . $code . " ,工作人员不会索取, 有效期五分钟, 请勿泄露";
        }

        $resultObj = $a->sendMessage($mobile, $content);
        if ($resultObj->Success == 1) {
            //        echo "发送成功";
            return $res = [
                'code' => '1',
                'msg' => '发送成功',
                'data' => '',
            ];

        } else {
            //        echo "发送失败， 失败原因： ".$resultObj->Message;
            return $res = [
                'code' => 0,
                'msg' => '发送失败',
                'data' => $resultObj->Message,
            ];
        }
    }
}

if (!function_exists('sms_notice')) {
    /**
     * 发送短信
     * @param $mobile
     * @param $code
     * @param $type 1 验证码 2 通知
     */
    function sms_notice($mobile, $content)
    {

        if (!check_mobile($mobile)) {
            return $res = [
                'code' => '-1',
                'msg' => '手机号码格式不正确',
                'data' => '',
            ];
        }

        $a = new \app\common\model\SmsLogic();
        $resultObj = $a->sendMessage($mobile, $content);
        if ($resultObj->Success == 1) {
            //        echo "发送成功";
            return $res = [
                'code' => '1',
                'msg' => '发送成功',
                'data' => '',
            ];

        } else {
            //        echo "发送失败， 失败原因： ".$resultObj->Message;
            return $res = [
                'code' => 0,
                'msg' => '发送失败',
                'data' => $resultObj->Message,
            ];
        }
    }
}


if (!function_exists('check_mobile')) {
    /**
     * 检查手机号码格式
     * @param $mobile 手机号码
     */
    function check_mobile($mobile)
    {
        if (preg_match('/1[34578]\d{9}$/', $mobile))
            return true;
        return false;
    }
}
